package com.keepers.repair.adapter

import android.content.Context
import android.media.MediaPlayer
import android.net.Uri
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.keepers.repair.R
import com.keepers.repair.model.ChatHistoryItemModel
import com.keepers.repair.utils.Api
import com.keepers.repair.utils.writeToDisk
import org.jetbrains.anko.find
import org.jetbrains.anko.toast
import java.io.File


class ChatHistoryAdapter(val list: List<ChatHistoryItemModel>) : RecyclerView.Adapter<ChatHistoryAdapter.ViewHolder>() {

    override fun getItemCount() = list.size
    override fun onCreateViewHolder(viewGroup: ViewGroup, position: Int): ViewHolder {
        val view = LayoutInflater.from(viewGroup.context).inflate(R.layout.item_chat_history, viewGroup, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = list[position]
        val name = if (item.Name.length > 18) "${item.Name.substring(0, 18)}..." else item.Name
        val type = item.DataType
        holder.name.text = name
        holder.date.text = item.ChattingDate
        holder.content.text = when (type) {
            "1001", "Text"  -> item.ChattingContent
            "1002", "Voice" -> "声音文件，点击播放"
            else -> "未知文件"
        }

        if (type == "Voice" || type == "1002") {
            holder.content.setOnClickListener { _ ->
                val context = holder.itemView.context
                val file = File("${context.cacheDir}/${item.ChattingContent}")
                if (!file.exists()) {
                    Api.downloadChatVoice(item.ChattingContent) { body ->
                        if (body == null) {
                            context.toast("声音文件下载出错")
                            return@downloadChatVoice
                        }
                        writeToDisk(item.ChattingContent, body)?.apply {
                            play(context, this)
                        }
                    }
                } else {
                    play(context, file)
                }
            }
        }
    }

    private fun play(context: Context, file: File) {
        val mediaPlayer = MediaPlayer.create(context, Uri.fromFile(file))
        mediaPlayer.start()
    }

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val name = view.find<TextView>(R.id.item_chat_history_username)
        val date = view.find<TextView>(R.id.item_chat_history_date)
        val content = view.find<TextView>(R.id.item_chat_history_content)
    }
}
